var ul=$("#dataDIV .order_list");
var contextPath = $("#contextPath").val();
var isload=true,isTab=true;
var state="";
var shoppingcartTips = $('.shoppingcart__tips');
var tabIndex=0;
var acceptTime = "";
var acceptStation = "正在加载物流信息...";
var arr = [];
var start=0,page=1,showNumber=6;
$(function() {
	dataInit();
});

function dataInit(){
	var status=$("#status").val();
	if(status!=null && status!='' && status!="empty"){
		state=status;
		var listTab=$("#listTab");
		listTab.remove();
	}else if(status=="empty"){
		state="";
		status=$("#status").val("");
		tabIndex=0;
	}
	$.ajax({
		url:"order/getOrderList",
		type:"post",
		async:true,
		dataType:"json",
		data:{start:start,showNumber:showNumber,"params['state']":state},
		success : function(data, textStatus) {
			isTab=true;
			$(".lodingStyle").hide();
			var state = data.result.state;
			html = '';
			if(state == 1){
				if(Object.getOwnPropertyNames(data.resOrderMap).length>0){
					$.each(data.resOrderMap,function(i,v){
						var stateDIV="";
						if(v.state=="00"){
							status="00";
							stateDIV="待付款";
						}else if(v.state=="01"){
							status="01";
							stateDIV="待发货";
						}else if(v.state=="02"){
							status="02";
							stateDIV="待收货";
						}else if(v.state=="03"){
							status="03";
							stateDIV="已完成";
						}else if(v.state=="04"){
							status="04";
							stateDIV="已取消";
						}
						html+='<li class="order_item">';
						if(status=="02"){
							html+=' <div class="mod_order_transport divOrderID"><div class="transport_icon icon_car"></div><dl class="order_transport_info" orderId='+v.id+'><dt class="dt_acceptStation">'+acceptStation+'</dt><dd class="g9 dt_acceptTime">'+acceptTime+'</dd></dl> </div>';
							arr.push(v.id);
						}
						html+='<div class="order_item_top"><div class="order_code f0"><a href="'+contextPath+'/order/detail.do?orderID='+v.order_id+'"><span class="icon_order_code dib vm"></span><span class="order_code_txt dib vm" id="orderID">订单号：'+v.order_id+'<em class="n">></em></span></a></div><div class="order_status" id="stateDIV"> '+stateDIV+'</div></div>';
						
						$.each(v.goodsList,function(j,item){
							html+='<div class="order_goods_item"><div class="goods_img" id="goodsThumb">';
							if(item.isPointsBuy == "01"){
								if(item.goodsThumb==null){
									html += '<i class="vip_mark"></i><img src="'+contextPath+'/static/images/icon_default_02.jpg" onclick="goodDateil('+item.goods_id+');"></div>';
								}else{
									html += '<i class="vip_mark"></i><img src="'+item.goodsThumb+'" onerror="this.src=\''+contextPath+'/static/images/icon_default_02.jpg\'" onclick="goodDateil('+item.goods_id+');"></div>';
								}
								if(item.usePrice == 0){
									html += '<div class="goods_info"><div class="order_goods_info"><p onclick="goodDateil('+item.goods_id+');" class="goods_info_name" id="goodsDescribe">'+item.title+'</p><div class="goods_info_price tr"> <p class="rebate"><em class="n">'+item.usePointsNum/item.number+'</em> 兑换券</p></div> </div>'
								}else{
									html += '<div class="goods_info"><div class="order_goods_info"><p onclick="goodDateil('+item.goods_id+');" class="goods_info_name" id="goodsDescribe">'+item.title+'</p><div class="goods_info_price tr"> <p class="rebate"><em class="n">'+item.usePointsNum/item.number+'</em> 兑换券</p><p class="rebate"> + <span>'+item.usePrice/item.number+'</span>元</p> </div> </div>'
								}
							}else{
								if(item.goodsThumb==null){
									html += '<img src="'+contextPath+'/static/images/icon_default_02.jpg" onclick="goodDateil('+item.goods_id+');"></div>';
								}else{
									html += '<img src="'+item.goodsThumb+'" onerror="this.src=\''+contextPath+'/static/images/icon_default_02.jpg\'" onclick="goodDateil('+item.goods_id+');"></div>';
								}
								html += '<div class="goods_info"><div class="order_goods_info"><p onclick="goodDateil('+item.goods_id+');" class="goods_info_name" id="goodsDescribe">'+item.title+'</p><div class="goods_info_price tr"> <p class="normal">&yen;'+item.currentPrice+'</p>';
								 if(item.returnPoints>0){
								    html+=' <p class="commodity__live_voucher">赠 <em class="n">'+item.returnPoints+'</em>兑换券</p></div> </div>';	
								    }else{
								    html+='</div> </div>';	
								    }
							}
							html+='<div class="order_goods_info"><p class="goods_info_color" id="goodsAttribute">'+item.specDesc+'</p><p class="goods_info_quantity" id="number"> X'+item.number+'</p></div></div></div>';
						});
						html+='<div class="order_item_remark"><span>共<b>'+v.sum+'</b>件商品</span><span>合计:<b>￥'+v.realPrice+'</b></span><span>(含运费<b>￥'+v.transitPrice+'</b>)</span></div>';
						if(status=="00"){
							//预留00-待付款状态
							html+='<div class="order_item_operating tr f0">'+
							'<a class="ui_btn" href="javascript:;" onclick="cancelWaitOrder('+v.order_id+',this);">取消订单</a>' +
							'<a class="ui_btn ui_btn_primary" href="javascript:;" onclick="payment('+v.order_id+');">&emsp;付款&emsp;</a></div>';
						}else if(status=="01"){
							//html+='<div class="order_item_operating tr f0"><a class="ui_btn" href="javascript:;" onclick="cancelOrder('+v.order_id+','+v.cur_pay_points+','+v.cur_pay_price+');">取消订单</a></div>';
						}else if(status=="02"){
							html+='<div class="order_item_operating tr f0" a_disabled="'+v.id+'"><a class="ui_btn disabledHref" disabled=true href="'+contextPath+'/courier/transport?orderId='+v.id+'">查看物流</a><a class="ui_btn ui_btn_primary" href="javascript:;" onclick="confirmGoods('+v.order_id+');">确认收货</a></div>';
						}
						
						html+='</li>';
					});
					ul.append(html);
					start=page*showNumber;
					page++;
					if(Object.getOwnPropertyNames(data.resOrderMap).length == showNumber){
						isload = true;
					}
				}
				goodsIsNull();
				
				//显示物流
				courierMessage(arr);
			}
		},
		error : function(XMLHttpRequest, textStatus, errorThrown){
			isTab=true;
			$(".lodingStyle").hide();
			layer.open({
			    content:textStatus,
			    time: 10000
			});
		}
	});		
}

function goodsIsNull(){
	if($(".order_code").length==0){
		shoppingcartTips.css('display','flex');
	}else{
		shoppingcartTips.hide();
	}
}

function goodDateil(goodID){
	window.location.href=contextPath+"/goods/detailPage?goodsId="+goodID;
}

function paramInit(){
	isload = true;
	$(".lodingStyle").show();
	start=0,page=1;
	ul.empty();
}

dropload.scroll(function(t){
	if(t<5&&isload&&isTab){
		$(".lodingStyle").show();
		isload = false;
		dataInit();
	}
});

var list = new Tab('.list__tab', {
  index: tabIndex,
  onClick: function onClick(tab) {
	  isTab = false;
	  paramInit();
	  if(tab.index == 0){
		  state="";
		  dataInit();
	  }else if(tab.index == 1){
		  state="01";
		  dataInit();
	  }else if(tab.index == 2){
		  state="02";
		  dataInit();
	  }else if(tab.index == 3){
		  state="03";
		  dataInit();
	  }
  }
});
function cancelOrder(id,cur_pay_points,cur_pay_price){
	$.ajax({
		url:contextPath+"/pay/cCancelOrder",
		type:"post",
		async:true,
		dataType:"json",
		data:{"orderID":id,"cur_pay_points":cur_pay_points,"cur_pay_price":cur_pay_price},
		success : function(data, textStatus) {
			var state = data.result.state;
			if(state == 1){
				var code = data.payCode;
				layer.open({
				    title: '提示',
				    content: '取消成功！',
				    btn: ['我知道了'],
				    yes: function(index){
				    	location.href=contextPath+"/order/getOrderList";
				    }
				});	
			}else{
				var message = data.result.message;
				var url = data.result.url;
				layer.open({
				    title: '提示',
				    content: message,
				    btn: ['我知道了'],
				    yes: function(index){
				    	layer.close(index);
				        if(url != null){
							location.href=contextPath+url;
						}
				    }
				});	
			}
		},error : function(XMLHttpRequest, textStatus, errorThrown){
			isTab=true;
			$(".lodingStyle").hide();
			layer.open({
			    title: '提示',
			    content: '支付失败，请重试',
			    btn: ['我知道了']
			});	
		}
	});
}

function cancelWaitOrder(orderId,self){
	var leg = 0;
	 layer.open({
		    content: '是否确认取消？'
		    ,btn: ['确认', '不要']
		    ,yes: function(index){		  
	$.ajax({
		url:contextPath+"/pay/cCancelWaitOrder",
		type:"post",
		async:true,
		dataType:"json",
		data:{"orderID":orderId},
		success : function(data, textStatus) {
			var state = data.result.state;
			if(state == 1){
				var code = data.payCode;
				layer.close(index)
				$(self).parents('.order_item').remove()
				leg =$('.order_list').find('.order_item').length;
				if(leg == 0){
					$('.shoppingcart__tips').css('display',"flex")
				}		
				
			}else{
				var message = data.result.message;
				var url = data.result.url;
				layer.open({
				    title: '提示',
				    content: message,
				    btn: ['我知道了'],
				    yes: function(index){
				    	layer.close(index);
				        if(url != null){
							location.href=contextPath+url;
						}
				    }
				});	
			}
		},error : function(XMLHttpRequest, textStatus, errorThrown){
			isTab=true;
			$(".lodingStyle").hide();
			layer.open({
			    title: '提示',
			    content: '操作失败，请重试',
			    btn: ['我知道了']
			});	
		}
	});
		    }
	  });
}

function payment(orderCode){
	layer.open({
	    type: 1,
	    content: '<dl class="layer_paying_method"><dt><p class="tc">请选择支付方式</p></dt><dd><a href="javascript:;" onclick="goWXWap('+orderCode+');" class="paying_method_01">微信支付</a></dd><dd><a href="javascript:;" onclick="goAliPayWap('+orderCode+');" class="paying_method_02">支付宝支付</a></dd></dl>',
	    anim: 0,
	    style: 'position:fixed; bottom:0; left:0; width:100%; height:8.6rem; padding:.5rem; border:none; box-sizing: border-box;'
	  });
}

function goAliPayWap(orderCode){
	load = layer.open({type: 2,shadeClose:false});
	$.ajax({
		url:contextPath+"/pay/confirm_alipay_unpaid",
		type:"post",
		async:true,
		data:{orderCode:orderCode},
		dataType:"json",
		success : function(data, textStatus) {
			var state = data.result.state;
			if(state == 1){
				var url = data.url;
				$('#alipay_box').append(url);
			}else{
				layer.close(load);
				layer.open({
				    title: '提示',
				    content: data.result.message,
				    btn: ['我知道了']
				});
			}
			
		},
		error : function(XMLHttpRequest, textStatus, errorThrown){
			layer.open({
			    content:textStatus,
			    time: 2
			});
		}
	});	
}

function goWXWap(orderCode){
	var url = null;
	var terminal = $('#terminal').val();
	if(terminal == 'app'){
		url = contextPath+"/pay/confirm_wxapp_unpaid";
	}else{
		url = contextPath+"/pay/confirm_wxjs_unpaid";
	}
	
	
	var load = layer.open({type: 2,shadeClose:false});
	$.ajax({
		url:url,
		type:"post",
		async:true,
		data:{orderCode:orderCode},
		dataType:"json",
		success : function(data, textStatus) {
			var state = data.result.state;
			if(state == 1){
				if(terminal == 'app'){
					var params = JSON.stringify(data.prePayInfo);
					window.location.href = "wechat://"+params; 
					layer.close(load);
				}else{
					doWxJsPay(data.prePayInfo,data.payCode);
					layer.close(load);
				}
				
			}else{
				layer.close(load);
				layer.open({
				    title: '提示',
				    content: data.result.message,
				    btn: ['我知道了']
				});
			}
			
		},
		error : function(XMLHttpRequest, textStatus, errorThrown){
			layer.open({
			    content:textStatus,
			    time: 2
			});
		}
	});	

}

function confirmGoods(id){
	$.ajax({
		url:"order/confirmGoods",
		type:"post",
		async:true,
		dataType:"json",
		data:{"params['orderID']":id},
		success : function(data, textStatus) {
			var state = data.result.state;
			if(state == 1){
				layer.open({
				    title: '提示',
				    content:data.result.message,
				    btn: ['我知道了']
				});
				ul.empty();
				start=0;
				status=$("#status").val("empty");
				dataInit();
			}
		},error : function(XMLHttpRequest, textStatus, errorThrown){
			isTab=true;
			$(".lodingStyle").hide();
			layer.open({
			    title: '提示',
			    content: '确认失败，请重试',
			    btn: ['我知道了']
			});	
		}
	});
}


function doWxJsPay(prePayInfo, code){
	if (typeof WeixinJSBridge == "undefined"){
		   if( document.addEventListener ){
		       document.addEventListener('WeixinJSBridgeReady', function(){
		    	   onBridgeReady(prePayInfo, code);
		       }, false);
		   }else if (document.attachEvent){
		       document.attachEvent('WeixinJSBridgeReady', function(){
		    	   onBridgeReady(prePayInfo, code);
		       }); 
		       document.attachEvent('onWeixinJSBridgeReady', function(){
		    	   onBridgeReady(prePayInfo, code);
		       });
		   }
		}else{
		   onBridgeReady(prePayInfo, code);
		}
}
function onBridgeReady(prePayInfo, code){
	WeixinJSBridge.invoke('getBrandWCPayRequest',prePayInfo,
		    function(res){
		       //支付成功或失败前台判断
    	       if(res.err_msg=='get_brand_wcpay_request:ok'){
    	    	   layer.open({
					    title: '提示',
					    content: '恭喜你，支付成功！',
					    btn: ['我知道了'],
					    yes: function(index){
					        layer.close(index);
					    	location.href=contextPath+"/pay/payOneResult?code="+code;
					    }
					});	
    	       }else if(res.err_msg=='get_brand_wcpay_request:cancel'){	
    	    	   layer.open({
					    title: '提示',
					    content: '支付已取消！',
					    btn: ['我知道了']
					});	
    	       }else{
    	    	   layer.open({
					    title: '提示',
					    content: '支付失败，请重试！',
					    btn: ['我知道了']
					});	
    	       }
		     });
	
}

function courierMessage(arr ,a_disabled){
	if(arr.length > 0){
		$.each(arr,function(i,v){
			$.ajax({
				url:contextPath+'/courier/orderTraces.do',
				type:"post",
				dataType:"json",
				async:true,
				data:{"orderId":v},
				success : function(data) {
					
					if(data.result.state == 1){
						if(data.State == "3"){
							$('dl[orderId = '+v+'] .dt_acceptStation').html("您的订单已签收！");
							$('dl[orderId = '+v+'] .dt_acceptTime').html(data.AcceptTime);
						}else if(data.State == "4"){
							$('dl[orderId = '+v+'] .dt_acceptStation').html("物流信息暂无更新!");
						}else if(data.State == "waitingExpCode"){
							$('dl[orderId = '+v+'] .dt_acceptStation').html("物流信息暂无！");//包裹正等待揽收！
						}else {
							$('dl[orderId = '+v+'] .dt_acceptStation').html(data.AcceptStation);
							$('dl[orderId = '+v+'] .dt_acceptTime').html(data.AcceptTime);
						}
						$('div[a_disabled = '+v+'] .disabledHref').attr('class',"ui_btn ui_btn_primary btn_paying");
					}else{
						//alert(data.result.message)
						if(data.State == "courierError"){
							$('dl[orderId = '+v+'] .dt_acceptStation').html("物流信息暂无！");
						}else if(data.State == "SuccessError"){
							$('dl[orderId = '+v+'] .dt_acceptStation').html("物流信息暂无！");//系统异常 : 信息返回失败！
						}else{
							$('dl[orderId = '+v+'] .dt_acceptStation').html("物流信息暂无！");//系统异常 : 请及时联系管理员！
						}
						$('div[a_disabled = '+v+'] .disabledHref').attr('href',"javascript:;");
					}
				},error : function(XMLHttpRequest, textStatus, errorThrown){
				}
			});
		});
	}
}
